package com.ruoyi.project.app.security.service;

import com.ruoyi.project.app.domain.UserEntity;
import com.ruoyi.project.app.mapper.UserMapper;
import com.ruoyi.project.app.security.domain.AppLoginUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Service
public class AppUserDetailsServiceImpl implements UserDetailsService
{
    private static final Logger log = LoggerFactory.getLogger(AppUserDetailsServiceImpl.class);

    @Autowired
    private UserMapper userDao;


    @Override
    public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException
    {
        //用户名 密码 权限控制
//        List<GrantedAuthority>authorities=new ArrayList<>();
//        GrantedAuthority grantedAuthority=new SimpleGrantedAuthority("admin");
//        authorities.add(grantedAuthority);
//        new User("username","pwd",authorities);

        List<UserEntity> appUsers = userDao.selectByUsername(account);
        if(appUsers.isEmpty()){
            log.info("登录用户：{} 不存在.", account);
            throw new UsernameNotFoundException("user：" + account + " does not exist");
        }
        return createLoginUser(appUsers.get(0));
    }

    public UserDetails createLoginUser(UserEntity user)
    {
        return new AppLoginUser(user);
    }
}
